package com.zsp.coupon.executor.impl;

import com.zsp.coupon.constant.RuleFlag;
import com.zsp.coupon.executor.AbstractExecutor;
import com.zsp.coupon.executor.RuleExecutor;
import com.zsp.coupon.vo.CouponTemplateSDK;
import com.zsp.coupon.vo.SettlementInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
@Slf4j
public class ManjianExecutor extends AbstractExecutor
        implements RuleExecutor {
        /**
         * 规则类型标记
         */
    @Override
    public RuleFlag ruleConfig() {

        return RuleFlag.MANJIAN;
    }

    /**
     优惠卷计算的规则 /**
     * <h2>优惠券规则的计算</h2>
     * @param settlement {@link SettlementInfo} 包含了选择的优惠券
     * @return {@link SettlementInfo} 修正过的结算信息
     * */
    @Override
    public SettlementInfo computeRule(SettlementInfo settlement) {
        double goodsSum = retain2Decimals(
                goodsCostSum(settlement.getGoodsInfos())
        );
        SettlementInfo probably = processGoodsTypeNotSatisfy(
                settlement,goodsSum
        );
        if (null !=probably) {
            log.debug("ManJian Template Is Not Match To GoodsType!");
            return probably;
        }
        // 判断满减是否符合折扣标准
         CouponTemplateSDK templateSDK = settlement
                        .getCouponAndTemplateInfo()
                        .get(0).getTemplate();
        double base = (double) templateSDK.getRule().getDiscount().getBase();
        double quota = (double) templateSDK.getRule().getDiscount().getQuota();

        // 如果不符合标准, 则直接返回商品总价
        if (goodsSum < base) {
            log.debug("Current Goods Cost Sum < ManJian Coupon Base!");
            settlement.setCost(goodsSum);
            settlement.setCouponAndTemplateInfo(Collections.emptyList());
                return settlement;
        }
        // 计算使用优惠券之后的价格 - 结算
            settlement.setCost(retain2Decimals
                    (goodsSum - quota > minCost() ? (goodsSum-quota):minCost()));
        log.debug("Use ManJian Coupon Make Goods Cost From {} To {}",
                goodsSum, settlement.getCost());

        return settlement;
    }
}
